package com.qfedu.fmmall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.common.status.ResStatus;
import com.qfedu.fmmall.common.vo.ResultVO;
import com.qfedu.fmmall.entity.ShoppingCart;
import com.qfedu.fmmall.entity.Users;
import com.qfedu.fmmall.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author : yanBin
 * @date :2021/12/13 17:07
 */
@RestController
@RequestMapping("/shopcart")
@Api(value = "提供购物车业务相关管理", tags = "购物车管理")
@CrossOrigin
public class ShoppingCartController {

    @Resource
    private ShoppingCartService shoppingCartService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/add")
    public ResultVO addShoppingCart(@RequestBody ShoppingCart shoppingCart, @RequestHeader("token") String token) {
        try {
            String s = stringRedisTemplate.boundValueOps(token).get();
            Users users = objectMapper.readValue(s, Users.class);
            System.out.println(users);
            return shoppingCartService.addShoppingCart(shoppingCart);
        } catch (Exception e) {
            return new ResultVO(ResStatus.NO.ordinal(), e.getLocalizedMessage(), null);
        }
    }

    @GetMapping("/list")
    @ApiImplicitParam(dataType = "int", name = "userid", value = "用户id", required = true)
    public ResultVO listShoppingCartByUserId(Integer userid, @RequestHeader("token") String token) {
        try {
            String s = stringRedisTemplate.boundValueOps(token).get();
            Users users = objectMapper.readValue(s, Users.class);
            System.out.println(s);
            return shoppingCartService.listShoppingCartByUserId(userid);
        } catch (Exception e) {
            return new ResultVO(ResStatus.NO.ordinal(), e.getLocalizedMessage(), null);
        }

    }

    @PutMapping("/update/{cid}/{cnum}")
    public ResultVO updateCartNum(@PathVariable("cid") Integer cid,
                                  @PathVariable String cnum,
                                  @RequestHeader("token") String token) {
        return shoppingCartService.updateCartNum(cid, cnum);
    }

    @GetMapping("/listbycids")
    @ApiImplicitParam(dataType = "String", name = "cids", value = "购物车id集合", required = true)
    public ResultVO listByCids(String cids, @RequestHeader("token") String token) {
        return shoppingCartService.listShoppingCatByCartsId(cids);
    }

}
